﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Globalization;
using System.IO;
using System.Collections;

namespace BingImages
{
    public partial class themeForm : Form
    {
        private Settings _settings;
        private Folder _folder;
        private Copy _copy;
        private ThemeDraw _themeDraw;
        private ToolTip _ttipConfirm;
        private ToolTip _ttipCancel;
        private ToolTip _ttipState;
        private BackgroundWorker bw = null;
        private string _archivePath = "";
        private bool _init = false;
        private int _oldYearIndex = 0;
        private int _oldMonthIndex = 0;
        private bool _mFirstClick = false;
        private Point _mFirstClickLoc;

        public themeForm()
        {
            InitializeComponent();

            // ------------ DEBUT TOOLTIP ------------ //
            this._ttipConfirm = new ToolTip();
            this._ttipConfirm.SetToolTip(btnConfirm, "Valider");

            this._ttipCancel = new ToolTip();
            this._ttipCancel.SetToolTip(btnCancel, "Annuler");

            this._ttipState = new ToolTip();
            this._ttipState.SetToolTip(this.ckbxState, "Fonctionnalité activée");
            // ------------ FIN TOOLTIP ------------ //

            this._settings = new Settings();
            this._folder = new Folder();
            this._copy = new Copy();
            this._themeDraw = new ThemeDraw(this);  

            this.init();            
        }

        private void init()
        {
            FileInfo[] files = null;
            ComboBoxItem cbiPreviousYear = null;
            ComboBoxItem cbiMonth = null;            
            string fileName = "";
            ArrayList yearsList = null;

            files = this._folder.getFiles("theme", "*.jpg");

            if (files.Count() > 0)
            {
                foreach (FileInfo file in files)
                {
                    this._themeDraw.setTheme(file.FullName);
                }
            }

            // ------------ DEBUT INITIALISATION COMBOBOX (cbxMonth && cbxYears) ------------ //
            cbiMonth = new ComboBoxItem();
            cbiMonth.Text = DateTime.Now.ToString("MMMM");
            cbiMonth.Value = DateTime.Now.Month.ToString("d2");

            this.cbxMonth.Items.Add(cbiMonth);

            cbiPreviousYear = new ComboBoxItem();
            cbiPreviousYear.Text = DateTime.Now.Year.ToString();
            cbiPreviousYear.Value = DateTime.Now.Year.ToString();

            this.cbxYears.Items.Add(cbiPreviousYear);

            this._archivePath = this._settings.path + @"\Archives";

            if (!string.IsNullOrEmpty(this._archivePath) && Directory.Exists(this._archivePath))
            {
                FileInfo[] yearsFiles = null;                
                string[] split = null;

                // ------------ DEBUT RECUPERATION FICHIERS ------------ //
                yearsFiles = this._folder.getFiles(new DirectoryInfo(this._archivePath), "*.zip");                
                // ------------ FIN RECUPERATION FICHIERS ------------ //

                yearsList = new ArrayList();
                yearsList.Add(DateTime.Now.Year.ToString());

                foreach (FileInfo file in yearsFiles)
                {
                    fileName = Path.GetFileNameWithoutExtension(file.Name);
                    split = fileName.Split('-');

                    if(!yearsList.Contains(split[2]))
                    {
                        yearsList.Add(split[2]);
                    }
                }

                yearsList.Sort();
                yearsList.Reverse();

                foreach (string years in yearsList)
                {
                    if(years != DateTime.Now.Year.ToString())
                    {
                        cbiPreviousYear = new ComboBoxItem();
                        cbiPreviousYear.Text = years;
                        cbiPreviousYear.Value = years;

                        this.cbxYears.Items.Add(cbiPreviousYear);
                    }
                }
            }

            this.setCbxMonth(this._archivePath, DateTime.Now.Year);
            this.cbxYears.SelectedIndex = 0;
            // ------------ FIN INITIALISATION COMBOBOX (cbxMonth && cbxYears) ------------ //

            // ------------ DEBUT INITIALISATION COMBOBOX (cbxTime) ------------ //
            if (!string.IsNullOrEmpty(this._settings.timeInterval))
            {
                int item = int.Parse(this._settings.timeInterval) / 60;

                this.cbxTime.SelectedItem = item.ToString();
            }
            else
            {
                this.cbxTime.SelectedIndex = 0;
            }
            // ------------ FIN INITIALISATION COMBOBOX (cbxTime) ------------ //

            // ------------ DEBUT INITIALISATION CHECKBOX (ckbxState) ------------ //
            if (!string.IsNullOrEmpty(this._settings.wallpaperScroll))
            {
                if (this._settings.wallpaperScroll == "False")
                {
                    this.ckbxState.Checked = false;
                }
            }
            // ------------ FIN INITIALISATION CHECKBOX (ckbxState) ------------ //

            _init = true;
        }

        private void setCbxMonth(string archivePath, int year)
        {
            if(!string.IsNullOrEmpty(archivePath))
            {
                FileInfo[] monthFiles = null;
                ArrayList monthList = null;
                string[] split = null;
                ComboBoxItem cbiPreviousMonth = null;
                string fileName = "";

                if (_init)
                {
                    this.cbxMonth.Items.Clear();
                    this.cbxMonth.Items.Add("-- Choisir --");

                    if (year == DateTime.Now.Year)
                    {
                        ComboBoxItem cbiMonth = new ComboBoxItem();
                        cbiMonth.Text = DateTime.Now.ToString("MMMM");
                        cbiMonth.Value = DateTime.Now.Month.ToString("d2");

                        this.cbxMonth.Items.Add(cbiMonth);
                    }
                }

                monthFiles = this._folder.getFiles(new DirectoryInfo(archivePath), "*-" + year + ".zip");

                monthList = new ArrayList();

                foreach (FileInfo file in monthFiles)
                {
                    fileName = Path.GetFileNameWithoutExtension(file.Name);
                    split = fileName.Split('-');

                    monthList.Add(split[1]);
                }

                monthList.Reverse();

                foreach (string month in monthList)
                {
                    cbiPreviousMonth = new ComboBoxItem();
                    cbiPreviousMonth.Text = DateTime.ParseExact(month, "MM", CultureInfo.CurrentCulture).ToString("MMMM");
                    cbiPreviousMonth.Value = month;

                    this.cbxMonth.Items.Add(cbiPreviousMonth);
                }
            }

            this.cbxMonth.SelectedIndex = 0;
            this._oldMonthIndex = this.cbxMonth.SelectedIndex;
        }

        private void toggleButton()
        {
            this.cbxYears.Enabled = !this.cbxYears.Enabled;
            this.cbxMonth.Enabled = !this.cbxMonth.Enabled;
            this.cbxTime.Enabled = !this.cbxTime.Enabled;
            this.flpPicture.Enabled = !this.flpPicture.Enabled;
            this.flpTheme.Enabled = !this.flpTheme.Enabled;
        }

        public ComboBox getCbxMonth()
        {
            return this.cbxMonth;
        }

        public FlowLayoutPanel getFlpPicture()
        {
            return this.flpPicture;
        }

        public FlowLayoutPanel getFlpTheme()
        {
            return this.flpTheme;
        }

        public ProgressBar getPbPicture()
        {
            return this.pbPicture;
        }

        #region EVENTS
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            // On arrête le thread s'il existe
            Theme.abortThread(); 

            if (this.ckbxState.Checked)
            {
                int minute = 0;            

                // ------------ DEBUT MODIFICATIONS FICHIER CONFIGURATION ------------ //
                minute = int.Parse(cbxTime.Text) * 60;
                this._settings.save("timeInterval", minute.ToString());
                // ------------ FIN MODIFICATIONS FICHIER CONFIGURATION ------------ //

                // Appel du thread
                Theme.setTheme("True", minute.ToString());
            }

            this._settings.save("wallpaperScroll", this.ckbxState.Checked.ToString());
            this.Close();
        }

        private void ckbxState_CheckedChanged(object sender, EventArgs e)
        {
            this.toggleButton();

            if (!ckbxState.Checked)
            {
                this.flpPicture.BackColor = Color.Lavender;
                this.flpTheme.BackColor = Color.Lavender;
                this.ckbxState.Image = Properties.Resources.off;
                this._ttipState.SetToolTip(this.ckbxState, "Fonctionnalité désactivée");
            }
            else
            {
                this.flpPicture.BackColor = Color.White;
                this.flpTheme.BackColor = Color.White;
                this.ckbxState.Image = Properties.Resources.on;
                this._ttipState.SetToolTip(this.ckbxState, "Fonctionnalité activée");
            }
        }

        private void cbxTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.flpPicture.Focus();
        }

        private void cbxMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbxMonth.SelectedIndex != 0)
            {
                if (this.cbxMonth.SelectedIndex != this._oldMonthIndex)
                {
                    FileInfo[] files = null;
                    string monthNumber = "";

                    monthNumber = (this.cbxMonth.SelectedItem as ComboBoxItem).Value.ToString();

                    this._themeDraw.init(monthNumber);

                    files = this._folder.getFiles("temp", "*-" + monthNumber + "-*.jpg");

                    foreach (FileInfo file in files)
                    {
                        bw = new BackgroundWorker();
                        bw.DoWork += bw_DoWork;
                        bw.RunWorkerAsync(file);
                    }

                    this.pbPicture.Visible = false;
                    this.pbPicture.Value = 0;
                }

                this._oldMonthIndex = this.cbxMonth.SelectedIndex;
                this.flpPicture.Focus();
            }
        }

        private void cbxYears_SelectedIndexChanged(object sender, EventArgs e)
        {
           if(_init)
           {
               if (this.cbxYears.SelectedIndex != this._oldYearIndex)
               {
                   this.setCbxMonth(this._archivePath, Convert.ToInt32((this.cbxYears.SelectedItem as ComboBoxItem).Value));
               }

               this._oldYearIndex = this.cbxYears.SelectedIndex;
           }

           this.flpPicture.Focus();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            FileInfo file = e.Argument as FileInfo;
            this._themeDraw.setDraw(file.FullName);
        }

        private void themeForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this._mFirstClick == false)
                {
                    this._mFirstClick = true;
                    this._mFirstClickLoc = new Point(e.X, e.Y);
                }

                this.Location = new Point(
                    this.Location.X + e.X - this._mFirstClickLoc.X,
                    this.Location.Y + e.Y - this._mFirstClickLoc.Y
                );
            }
            else
            {
                this._mFirstClick = false;
            }
        }

        private void flpPicture_MouseEnter(object sender, EventArgs e)
        {
            this.flpPicture.Focus();
        }

        private void flpTheme_MouseEnter(object sender, EventArgs e)
        {
            this.flpTheme.Focus();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this._themeDraw.clear();
            this.Close();
        }
        #endregion
    }
}
